package xyz.jcat.generator.mybatis;

import xyz.jcat.common.util.StringUtils;

import java.util.Random;

public class StringConvertUtils {

    public static final int DIFFERENCE_a_AND_A = 'a' - 'A';
    public static final char[] NUMBER_WORDS =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                    'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                    'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
                    'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                    'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
                    'y', 'z'};

    /**
     * 下划线转驼峰
     *
     * @param field
     * @return
     */
    public static String underlineToCamel(String field) {
        return underlineToCamel(field, false);
    }

    /**
     * 类名下划线转驼峰
     *
     * @param str
     * @return
     */
    public static String underlineToCamel4ClassName(String str) {
        return underlineToCamel(str, true);
    }

    private static String underlineToCamel(String str, boolean includeFirstWord) {
        if (StringUtils.isEmpty(str)) {
            return str;
        }
        String[] words = str.split("_");
        StringBuilder sb = new StringBuilder(includeFirstWord ? "" : words[0]);
        int start = includeFirstWord ? 0 : 1;
        for (int i = start; i < words.length; i++) {
            sb.append(firstToUppercase(words[i]));
        }
        return sb.toString();
    }

    /**
     * 首字母变为大写
     *
     * @param words
     * @return
     */
    public static String firstToUppercase(String words) {
        if (StringUtils.isEmpty(words)) {
            return words;
        }
        char[] chars = words.toCharArray();
        char firstLetter = chars[0];
        if (firstLetter >= 'a' && firstLetter <= 'z') {
            chars[0] = (char) (firstLetter - DIFFERENCE_a_AND_A);
            return new String(chars);
        }
        return words;
    }

    public static String getRandomString(int length) {
        char[] chars = new char[length];
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            chars[i] = NUMBER_WORDS[random.nextInt(NUMBER_WORDS.length)];
        }
        return new String(chars);
    }

}
